package cc.mrbird.unit.service.impl;

import cc.mrbird.common.domain.QueryRequest;
import cc.mrbird.common.exception.FileImportException;
import cc.mrbird.common.service.impl.BaseService;
import cc.mrbird.management.domain.ManagementInstitutions;
import cc.mrbird.plan.domain.Inspection;
import cc.mrbird.plan.domain.InspectionAssetMana;
import cc.mrbird.system.domain.User;
import cc.mrbird.unit.dao.*;
import cc.mrbird.unit.domain.*;
import cc.mrbird.unit.service.UnitInfoService;
import cc.mrbird.unit.service.UnitTypeService;
import cc.mrbird.unit.service.UserUnitService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service("unitInfoService")
public class UnitInfoServiceImpl extends BaseService<UnitInfo> implements UnitInfoService {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UnitInfoMapper unitInfoMapper;
    @Autowired
    private UserUnitMapper userUnitMapper;
    @Autowired
    private UserUnitService userUnitService;
    @Autowired
    private ContactInforMapper contactInforMapper;
    @Autowired
    private AuxiliaryInforMapper auxiliaryInforMapper;
    @Override
    public List<UnitInfo> findUnitInfoWithType(UnitInfo unitInfo, QueryRequest request) {
        try {
            List<UnitInfo> unitInfoList = new ArrayList<>();
            List<UnitInfo> unitInfoWithType = this.unitInfoMapper.findUnitInfoWithType(unitInfo);
            for (UnitInfo info : unitInfoWithType) {
                Long contact_id = info.getContact_id(); //获取联络信息id
                ContactInfor contactInfor = contactInforMapper.findById(contact_id);
                //添加联络信息内容
                info.setContact_name(contactInfor.getContact_name());
                info.setContact_card(contactInfor.getContact_card());
                info.setContact_role_name(contactInfor.getContact_role_name());
                info.setContact_address(contactInfor.getContact_address());
                info.setContact_phone(contactInfor.getContact_phone());
                info.setContact_mail(contactInfor.getContact_mail());
                Long auxiliary_id = info.getAuxiliary_id();  //获取辅助信息id
                AuxiliaryInfor auxiliaryInfor = auxiliaryInforMapper.findById(auxiliary_id);
                info.setFloor_plan(auxiliaryInfor.getFloor_plan());
                info.setLocation_map(auxiliaryInfor.getLocation_map());
                info.setChannel_infor(auxiliaryInfor.getChannel_infor());
                unitInfoList.add(info);
            }
            return unitInfoList;
        } catch (Exception e) {
            log.error("error", e);
            return new ArrayList<>();
        }
    }

    @Override
    public UnitInfo findByName(String unit_name) {
        Example example = new Example(User.class);
        example.createCriteria().andCondition("lower(unit_name)=", unit_name.toLowerCase());
        List<UnitInfo> list = this.selectByExample(example);
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public void add(UnitInfo unitInfo,User user) {
        this.save(unitInfo);
        this.setUserUnits(unitInfo,user);
    }
    private void setUserUnits(UnitInfo unitInfo,User user) {
        UserUnit  userUnit = new UserUnit();
        userUnit.setUser_id(user.getUserId());
        userUnit.setUnit_id(unitInfo.getUnit_id());
        this.userUnitMapper.insert(userUnit);
    }
    @Override
    public void update(UnitInfo unitInfo) {
        this.updateNotNull(unitInfo);
    }

    @Override
    public UnitInfo findById(Long id) {
        try {
            UnitInfo info = this.unitInfoMapper.findById(id);
            Long contact_id = info.getContact_id(); //获取联络信息id
            ContactInfor contactInfor = contactInforMapper.findById(contact_id);
            //添加联络信息内容
            info.setContact_name(contactInfor.getContact_name());
            info.setContact_card(contactInfor.getContact_card());
            info.setContact_role_name(contactInfor.getContact_role_name());
            info.setContact_address(contactInfor.getContact_address());
            info.setContact_phone(contactInfor.getContact_phone());
            info.setContact_mail(contactInfor.getContact_mail());
            Long auxiliary_id = info.getAuxiliary_id();  //获取辅助信息id
            AuxiliaryInfor auxiliaryInfor = auxiliaryInforMapper.findById(auxiliary_id);
            info.setFloor_plan(auxiliaryInfor.getFloor_plan());
            info.setLocation_map(auxiliaryInfor.getLocation_map());
            info.setChannel_infor(auxiliaryInfor.getChannel_infor());
            return info;
        } catch (Exception e) {
            log.error("error", e);
            return new UnitInfo();
        }
    }

    @Override
    public boolean batchImport(String fileName, MultipartFile file) throws Exception {
        boolean notNull = false;
        List<UnitInfo> unitInfoList = new ArrayList<UnitInfo>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new FileImportException("上传文件格式不正确");
        }
        boolean isExcel2003 = false;
        if (fileName.matches("^.+\\.(?i)(xls)$")) {
            isExcel2003 = true;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (!isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if(sheet!=null){
            notNull = true;
        }
        UnitInfo unitInfo;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }

            unitInfo = new UnitInfo();

            String unit_name = row.getCell(0).getStringCellValue();
            if(unit_name == null || unit_name.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,单位名称未填写)");
            }
            String type_id =row.getCell(1).getStringCellValue();
            if(type_id==null || type_id.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,单位类型id未填写)");
            }
            String unit_address = row.getCell(2).getStringCellValue();
            if(unit_address==null ||unit_address.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,单位地址未填写)");
            }
            String attribution_grid = row.getCell(3).getStringCellValue();
            if(attribution_grid==null ||attribution_grid.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,归属网格未填写)");
            }
            String unit_legal = row.getCell(4).getStringCellValue();
            if(unit_legal==null ||unit_legal.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,单位法人未填写)");
            }
            row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
            String unit_phone = row.getCell(5).getStringCellValue();
            if(unit_phone==null ||unit_phone.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,单位电话未填写)");
            }
            String building_developer = row.getCell(6).getStringCellValue();
            if(building_developer==null ||building_developer.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,建筑开发商未填写)");
            }
            String building_contact = row.getCell(7).getStringCellValue();
            if(building_contact==null ||building_contact.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,建筑开发商联系人未填写)");
            }
            row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
            String building_phone = row.getCell(8).getStringCellValue();
            if(building_phone==null ||building_phone.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,建筑开发商电话未填写)");
            }
            String construction_unit = row.getCell(9).getStringCellValue();
            if(construction_unit==null ||construction_unit.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,消防工程施工单位未填写)");
            }
            String construction_contact = row.getCell(10).getStringCellValue();
            if(construction_contact==null ||construction_contact.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,消防工程施工单位联系人未填写)");
            }
            row.getCell(11).setCellType(Cell.CELL_TYPE_STRING);
            String construction_phone = row.getCell(11).getStringCellValue();
            if(construction_phone==null ||construction_phone.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,消防工程施工单位电话未填写)");
            }
            String property_management = row.getCell(12).getStringCellValue();
            if(property_management==null ||property_management.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,物业管理未填写)");
            }
            String property_contact = row.getCell(13).getStringCellValue();
            if(property_contact==null ||property_contact.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,物业管理联系人未填写)");
            }
            row.getCell(14).setCellType(Cell.CELL_TYPE_STRING);
            String property_phone = row.getCell(14).getStringCellValue();
            if(property_phone==null ||property_phone.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,物业联系人电话未填写)");
            }
            unitInfo.setUnit_name(unit_name);
            unitInfo.setType_id(Long.parseLong(type_id));
            unitInfo.setUnit_address(unit_address);
            unitInfo.setAttribution_grid(attribution_grid);
            unitInfo.setUnit_legal(unit_legal);
            unitInfo.setUnit_phone(unit_phone);
            unitInfo.setBuilding_developer(building_developer);
            unitInfo.setBuilding_contact(building_contact);
            unitInfo.setBuilding_phone(building_phone);
            unitInfo.setConstruction_unit(construction_unit);
            unitInfo.setConstruction_contact(construction_contact);
            unitInfo.setConstruction_phone(construction_phone);
            unitInfo.setProperty_management(property_management);
            unitInfo.setProperty_contact(property_contact);
            unitInfo.setProperty_phone(property_phone);

            unitInfoList.add(unitInfo);
        }
        for (UnitInfo unitInfo1 : unitInfoList) {
            String unit_name = unitInfo1.getUnit_name();
            int cnt = unitInfoMapper.selectByName(unit_name);
            if (cnt == 0) {
                this.save(unitInfo1);
            } else {
                this.update(unitInfo1);
            }
        }
        return notNull;
    }

    @Override
    @Transactional
    public void delete(String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        this.batchDelete(list, "unit_id", UnitInfo.class);
        this.userUnitService.deleteUserUnitByUnitId(ids);
    }
}
